package com.itheima.controller;

import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.pojo.dto.LoginDTO;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 手机验证码登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        log.info("member login");
        // 1. 验证基本参数
        if (loginDTO.getTelephone() == null || loginDTO.getTelephone().length() != 11){
            return new Result(false, "手机号码格式不正确");
        }
        if (!StringUtils.hasText(loginDTO.getValidateCode())){
            return new Result(false, "验证码不能为空");
        }
        // 2. 验证码校验 - 使用正确的Redis常量
        String redisCode = redisTemplate.opsForValue().get(
            RedisMessageConstant.SENDTYPE_LOGIN + loginDTO.getTelephone());
        if (redisCode == null) {
            return new Result(false, "验证码已过期，请重新获取");
        }
        if (!redisCode.equals(loginDTO.getValidateCode())) {
            return new Result(false, "验证码错误");
        }
        //3.调用接口完成登录
        memberService.login(loginDTO);
        // 4. 登录成功后删除验证码
        redisTemplate.delete(RedisMessageConstant.SENDTYPE_ORDER + loginDTO.getTelephone());
        return new Result(true, "登录成功");
    }

}
